<?php
// public/users.php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();

$user = current_user();
if ($user['role'] !== 'super') {
    header('Location: dashboard.php');
    exit;
}

$msg = null;
$type = 'success';

// --- Add user ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_user'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = $_POST['role'];

    try {
        $stmt = $pdo->prepare("
            INSERT INTO users (name, email, password, role, status, created_at)
            VALUES (?, ?, ?, ?, 'active', NOW())
        ");
        $stmt->execute([$name, $email, $password, $role]);

        header("Location: users.php?msg=User+added+successfully&type=success");
        exit;
    } catch (PDOException $e) {
        header("Location: users.php?msg=Error:+Email+already+exists&type=danger");
        exit;
    }
}

// --- Update user ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_user'])) {
    $id = $_POST['id'];
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $role = $_POST['role'];
    $status = $_POST['status'];

    try {
        if (!empty($_POST['password'])) {
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET name=?, email=?, password=?, role=?, status=? WHERE id=?");
            $stmt->execute([$name, $email, $password, $role, $status, $id]);
        } else {
            $stmt = $pdo->prepare("UPDATE users SET name=?, email=?, role=?, status=? WHERE id=?");
            $stmt->execute([$name, $email, $role, $status, $id]);
        }

        header("Location: users.php?msg=User+updated+successfully&type=success");
        exit;
    } catch (PDOException $e) {
        header("Location: users.php?msg=Error:+Could+not+update&type=danger");
        exit;
    }
}

// --- Delete user ---
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id=?");
        $stmt->execute([$id]);
        header("Location: users.php?msg=User+deleted+successfully&type=success");
        exit;
    } catch (PDOException $e) {
        header("Location: users.php?msg=Error:+Could+not+delete&type=danger");
        exit;
    }
}

// --- Fetch all accounts ---
$stmt = $pdo->query("SELECT id, name, email, role, status, created_at FROM users ORDER BY created_at DESC");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

$title = "Users | JO & COS RMS";
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<section class="content-header">
  <div class="container-fluid">
    <h1>Users <small class="text-muted">Manage Accounts</small></h1>
  </div>
</section>

<section class="content">
  <div class="container-fluid">

    <?php if (isset($_GET['msg'])): ?>
      <div class="alert alert-<?= htmlspecialchars($_GET['type'] ?? 'info') ?> alert-dismissible fade show" role="alert">
        <?= htmlspecialchars($_GET['msg']) ?>
        <button type="button" class="close" data-dismiss="alert">&times;</button>
      </div>
    <?php endif; ?>

    <div class="card">
      <div class="card-header">
        <a class="btn btn-primary" href="users.php">
          <i class="fas fa-user"></i> User
        </a>
		 <a class="btn btn-primary" href="unit.php">
          <i class="fas fa-user"></i> Unit
        </a>
		 <a class="btn btn-primary" href="jobtitle.php">
          <i class="fas fa-user"></i> Jobtitle
        </a>
      </div>
      <div class="card-body table-responsive">
	  
	   <button class="btn btn-primary" data-toggle="modal" data-target="#addUserModal">
          <i class="fas fa-plus"></i> Add User
        </button>
        <table id="usersTable" class="table table-bordered table-striped nowrap" style="width:100%">
          <thead>
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Email</th>
              <th>Role</th>
              <th>Status</th>
              <th>Created</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($users as $u): ?>
            <tr>
              <td><?= $u['id'] ?></td>
              <td><?= htmlspecialchars($u['name']) ?></td>
              <td><?= htmlspecialchars($u['email']) ?></td>
              <td><span class="badge badge-info"><?= $u['role'] ?></span></td>
              <td>
                <?php if ($u['status'] === 'active'): ?>
                  <span class="badge badge-success">Active</span>
                <?php else: ?>
                  <span class="badge badge-secondary"><?= htmlspecialchars($u['status']) ?></span>
                <?php endif; ?>
              </td>
              <td><?= $u['created_at'] ?></td>
              <td>
                <button class="btn btn-sm btn-warning mb-1" data-toggle="modal" data-target="#editUserModal<?= $u['id'] ?>">
                  <i class="fas fa-edit"></i>
                </button>
                <a href="?delete=<?= $u['id'] ?>" class="btn btn-sm btn-danger mb-1" onclick="return confirm('Delete this user?')">
                  <i class="fas fa-trash"></i>
                </a>
              </td>
            </tr>

            <!-- Edit Modal -->
            <div class="modal fade" id="editUserModal<?= $u['id'] ?>" tabindex="-1">
              <div class="modal-dialog modal-md">
                <div class="modal-content">
                  <form method="post">
                    <input type="hidden" name="id" value="<?= $u['id'] ?>">
                    <div class="modal-header">
                      <h5 class="modal-title">Edit User</h5>
                      <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                      <div class="form-group"><label>Name</label>
                        <input type="text" name="name" value="<?= htmlspecialchars($u['name']) ?>" class="form-control" required>
                      </div>
                      <div class="form-group"><label>Email</label>
                        <input type="email" name="email" value="<?= htmlspecialchars($u['email']) ?>" class="form-control" required>
                      </div>
                      <div class="form-group"><label>Password (leave blank to keep current)</label>
                        <input type="password" name="password" class="form-control">
                      </div>
                      <div class="form-group"><label>Role</label>
                        <select name="role" class="form-control" required>
                          <option value="staff" <?= $u['role']=='staff'?'selected':'' ?>>Staff</option>
                          <option value="admin" <?= $u['role']=='admin'?'selected':'' ?>>Admin</option>
                        </select>
                      </div>
                      <div class="form-group"><label>Status</label>
                        <select name="status" class="form-control" required>
                          <option value="active" <?= $u['status']=='active'?'selected':'' ?>>Active</option>
                          <option value="inactive" <?= $u['status']=='inactive'?'selected':'' ?>>Inactive</option>
                        </select>
                      </div>
                    </div>
                    <div class="modal-footer">
                      <button type="submit" name="edit_user" class="btn btn-primary">Save</button>
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                  </form>
                </div>
              </div>
            </div>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</section>

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1">
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <form method="post">
        <div class="modal-header">
          <h5 class="modal-title">Add User</h5>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group"><label>Name</label><input type="text" name="name" class="form-control" required></div>
          <div class="form-group"><label>Email</label><input type="email" name="email" class="form-control" required></div>
          <div class="form-group"><label>Password</label><input type="password" name="password" class="form-control" required></div>
          <div class="form-group"><label>Role</label>
            <select name="role" class="form-control" required>
              <option value="staff" selected>Staff</option>
              <option value="admin">Admin</option>
            </select>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="add_user" class="btn btn-primary">Save</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css"/>
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap4.min.css"/>

<script>
$(function () {
  $('#usersTable').DataTable({
    responsive: true,
    autoWidth: false
  });
});
</script>
